package com.eling.elcms.richtexteditor.ueditor.controller;

import com.baidu.ueditor.ActionEnter;
import com.eling.elcms.core.service.RemotePriorityPropertyPlaceholderConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

/**
 * UEditor文件上传
 */
@WebServlet(name = "UEditorController", urlPatterns = {"/richeditor/richtexteditor/ueditorcontroller"})
public class UEditorController extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private static final String configStr = "/WEB-INF/config";
    private static final String fileProperties = File.separator + "file.properties";
    
    private static final Logger log = LoggerFactory.getLogger(UEditorController.class);
    
    private String rootPath;
    
    public UEditorController() {
        super();
    }

	/**
	 * 上传UEditor编辑器文件
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		try{
			request.setCharacterEncoding( "utf-8" );
			response.setHeader("Content-Type" , "text/html");

			String fileBasedir = RemotePriorityPropertyPlaceholderConfigurer.getPropertyValue("file.basedir");
			String ueditorBasedir = RemotePriorityPropertyPlaceholderConfigurer.getPropertyValue("ueditor.basedir");
			String appEnvId = RemotePriorityPropertyPlaceholderConfigurer.getPropertyValue("app.envId");


			rootPath =   fileBasedir.substring(1) + ueditorBasedir;
			
			String configPath = request.getSession().getServletContext().getRealPath(configStr);
			
			String responseStr = new ActionEnter( request, rootPath, configPath ).exec();
			
//			URL tUrl = new URL(rootPath);

			responseStr = responseStr.replace("${app.build.finalName}", appEnvId);
			
			response.getWriter().append(responseStr);
		}catch(Exception e){
			log.error(e.getMessage(), e);
		}
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
